Control statements
Control statements in Java are actually the same as C and will involve knives including if-else, while, do-while, for, return, break, switch.
Conditional statements
if statements
int a = 10;
if(a > 10){
return true;
}
return false;
if.. .else statement
int a = 10;
int b = 11;
if(a >= b){
System.out.println("a >= b");
}else{
System.out.println("a < b");
}
if.. .else if Multi-branch statements
int x = 40;
if(x > 60) {
System.out.println("The value of x is greater than 60");
} else if (x > 30) {
System.out.println("The value of x is greater than 30 but less than 60");
} else if (x > 0) {
System.out.println("The value of x is greater than 0 but less than 30");
} else {
System.out.println("The value of x is less than or equal to 0");
}
switch multi-branch statement
switch (week) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("No Else");
break;
}
Loop statements
while loop statement
while (boolean) {
expression
}
do... .while loop statement
The only difference between a while and a do... ...while loop is that the do... while statement is executed at least once.
int b = 10;
do {
System.out.println("b == " + b);
b--;
} while(b == 1);
for loop statement
for(initialize; Boolean expression; step) {}
The boolean expression is tested before each iteration, and if the result obtained is false, the code following the for statement is executed; at the end of each loop, the next loop is executed according to the value of the step.
Comma operator
A series of comma-separated statements can be used in the initialisation part of a for statement expression; the comma operator allows multiple variables to be defined within a for statement.
for(int i = 1; j = i + 10;i < 5;i++, j = j * 2){}
for-each statement
The for-each statement is a more introductory and convenient way of traversing arrays and collections.
int array[] = {7, 8, 9};
for (int arr : array) {
System.out.println(arr);
}
Jump statements
break statement
Terminates the loop
continue statement
Leaves the current loop and executes the next one.
return statement
The return statement